<?php

if (!class_exists('WP_List_Table')) {
	require_once(ABSPATH . 'wp-admin/includes/class-wp-list-table.php');
}

class SaleSea_Tasks_Table extends WP_List_Table {

	function __construct() {
		parent::__construct(array(
			'singular' => '任务列表',
			'plural'   => '任务列表',
			'per_page' => 10,
			'ajax'     => false,
		));
	}

	function get_columns() {
		$columns = array(
			'cb'       => '<input type="checkbox" />',
			'id' => 'ID',
			'keyword'    => '关键词',
			'title'  => '标题',
			'status' => '状态',
			'prompt' => '指令',
			'taskid' => '任务ID',
			'related' => '关联词',
			'created_at' => '创建时间',
		);
		return $columns;
	}

	function column_default($item, $column_name) {
		if($column_name === "prompt"){
			return substr($item->$column_name, 0 ,50);
		}else if($column_name === "status"){
		    switch($item->$column_name){
			    case 0:
					return "等待插入";
			    case 1:
					return "插入队列";
			    case 2:
					return "成功生成";
			    case 3:
					return "任务超市";
			    default:
					return "出现错误";
		    }
		}else{
			return $item->$column_name;
		}
	}

	public function pagination( $which ) {
		global $wpdb;

		$per_page = $this->get_items_per_page( 'posts_per_page', 10 );
		$page_num = $this->get_pagenum();
		$table_name = $wpdb->prefix."salesea_tasks";
		$total_items = $wpdb->get_var( "SELECT COUNT(*) FROM $table_name");

		$paginate_args = array(
			'total_items' => $total_items,
			'per_page'    => $per_page
		);

		$this->pagination = paginate_links( $paginate_args );
	}

	function prepare_items() {
		global $wpdb;
		$table_name = $wpdb->prefix."salesea_tasks";
		$columns = $this->get_columns();
		$hidden = array();
		$sortable = array();

		$per_page = 15;
		$current_page = $this->get_pagenum();

		$total_items = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
		$this->set_pagination_args(array(
			'total_items' => $total_items,
			'per_page' => $per_page
		));

		$offset = ( $current_page - 1 ) * $per_page;

		$this->_column_headers = array($columns, $hidden, $sortable);
		$query = "SELECT * FROM $table_name ORDER BY id DESC LIMIT $per_page OFFSET $offset";
		$items = $wpdb->get_results($query);

		$this->items = $items;
	}

	public function get_sortable_columns()
	{
		return array('id' => array('id', false));
	}
}

function custom_table_menu() {
	add_menu_page('SALESEA任务列表', 'SALESEA任务列表', 'manage_options', 'salesea-tasks', 'salesea_tasks_page', 'dashicons-chart-pie');
}
add_action('admin_menu', 'custom_table_menu');

function salesea_tasks_page() {
	$customTableList = new SaleSea_Tasks_Table();
	$customTableList->prepare_items();
	?>
	<div class="wrap">
		<h1>任务列表</h1>
		<form method="post">
			<?php $customTableList->search_box('Search', 'search_id'); ?>
			<?php $customTableList->display(); ?>
		</form>
	</div>
	<?php
}